package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	etcd "github.com/teamones-open/etcd-discovery"
	"github.com/teamones-open/etcd-discovery/etcd_api"
	"io/ioutil"
	"net/http"
	"time"
)

type TeamonesRequest struct {
}

// 请求用的client
var client *http.Client

// etcd的地址
var etcdHost string

// 请求10秒超时
var timeOut = 30 * time.Second

func init() {
	client = &http.Client{Timeout: timeOut}
}

// getServerNode 获得server 信息
func (t TeamonesRequest) getServerNode(serviceName string) (etcd_api.NodeInfo, error) {
	etcdHost = viper.GetString("etcd.host")
	return etcd.GetServerNodeByName(serviceName, etcdHost)
}

// Do 请求
func (t TeamonesRequest) Do(serviceName, endpoint string, params interface{}, headers map[string]string, res interface{}) (err error) {
	node, err := t.getServerNode(serviceName)
	if err != nil {
		return
	}
	bytesData, _ := json.Marshal(params)

	req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/%s", node.Addr, endpoint), bytes.NewReader(bytesData))
	if err != nil {
		return
	}
	// 添加默认的请求体类型声明
	req.Header.Add("Content-Type", "application/json;charset=UTF-8")
	if len(headers) > 0 {
		for k, v := range headers {
			req.Header.Add(k, v)
		}
	}
	resp, err := client.Do(req)
	if err != nil {
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	err = json.Unmarshal(body, &res)

	return
}
